﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

using System.Linq.Expressions;
using System.ComponentModel;

namespace WebSearch.Helpers
{
    static public class FormHelper
    {
        public static MvcHtmlString CheckboxList<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, IEnumerable<string>>> expression, Type enumType)
        {
            System.Text.StringBuilder html = new System.Text.StringBuilder();
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
            IEnumerable<string> currentValues = (IEnumerable<string>)metadata.Model;
            var values = Enum.GetValues(enumType);

            foreach (var value in values)
            {
                html.AppendFormat("<span><label class=\"checkbox\"><input type=\"checkbox\" name=\"{0}\" value=\"{1}\"{3} /> {2}</label></span> ",
                    metadata.PropertyName, value.ToString(), GetDisplayName(value),
                    (currentValues != null && currentValues.Contains(value.ToString()) ? " checked=\"checked\"" : "")
                );
            }

            return new MvcHtmlString(html.ToString());
        }

        private static String GetDisplayName(object value)
        {
            System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString());

            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if ((attributes != null) && (attributes.Length > 0))
                return attributes[0].Description;
            else
                return value.ToString();
        }
    }
}